package com.hqd.ch03.v48.boot.origin;

import java.util.*;

/**
 * 配置属性的来源
 */
public interface Origin {

    static Origin from(Object source) {
        if (source instanceof Origin) {
            return (Origin) source;
        }
        Origin origin = null;
        if (source instanceof OriginProvider) {
            origin = ((OriginProvider) source).getOrigin();
        }
        if (origin == null && source instanceof Throwable) {
            return from(((Throwable) source).getCause());
        }
        return origin;
    }

    static List<Origin> parentsFrom(Object source) {
        Origin origin = from(source);
        if (origin == null) {
            return Collections.emptyList();
        }
        Set<Origin> parents = new LinkedHashSet<>();
        origin = origin.getParent();
        while (origin != null && !parents.contains(origin)) {
            parents.add(origin);
            origin = origin.getParent();
        }
        return Collections.unmodifiableList(new ArrayList<>(parents));
    }

    /**
     * 获取父节点
     *
     * @return
     */
    default Origin getParent() {
        return null;
    }
}